//
//  HLEImageUploadRequest.m
//  HLENetwork_Example
//
//  Created by hle1879 on 2020/10/9.
//  Copyright © 2020 13434436448@163.com. All rights reserved.
//

#import "HLEImageUploadRequest.h"
#import <AFNetworking/AFNetworking.h>
#import "HLESessionManager.h"
#import "HLEBaseResponse.h"

@interface HLEImageUploadRequest ()

@property (nonatomic,strong) NSURLSessionDataTask *task;

@end

@implementation HLEImageUploadRequest

-(instancetype)init{
    self = [super init];
    if (self) {
        self.method = HLERequestMethodPOST;
        self.imageScale = 1.f;
        self.imageType = @"jpeg";
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        self.imageFileName = dateString;
        self.name = @"file";
    }
    return self;
}

- (void)sendRequest{
    [self addDelegateForDataTask];
    [self logRequestInfo];
    if (self.imageScale == 0 || self.imageScale > 1) {
        self.imageScale = 1;
    }
    if (!self.imageFileName) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        self.imageFileName = dateString;
    }
    if (!self.url) {
        self.url = @"";
    }
    NSError *error = nil;
    __weak typeof(self) weakSelf = self;
    NSMutableURLRequest *request = [self.session.sessionManager.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:self.url relativeToURL:self.session.config.baseURL] absoluteString] parameters:[self disposePublicParameters] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSData *imageData = UIImageJPEGRepresentation(obj, strongSelf.imageScale);
            [formData appendPartWithFileData:imageData name:(strongSelf.name ? strongSelf.name : @"file") fileName:[NSString stringWithFormat:@"%@%ld.%@", strongSelf.imageFileName, idx, (strongSelf.imageType ? strongSelf.imageType : @"jpeg")] mimeType:[NSString stringWithFormat:@"image/%@", (strongSelf.imageType ? strongSelf.imageType : @"jpeg")]];
        }];
    } error:&error];
    if (error) {
        HLEBaseResponse *result = [[HLEBaseResponse alloc]initWithResponse:nil responseObject:nil error:error];
        self.responseCompletion ? self.responseCompletion(result) : nil;
        [self removeDelegateForDataTask];
        [self logResponseInfo:result];
        return;
    }
    [self disposeRequestMutableHeaderField:request];
    self.task = [self.session.sessionManager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.progress ? strongSelf.progress(uploadProgress, uploadProgress.fractionCompleted) : nil;
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        HLEBaseResponse *result = [[HLEBaseResponse alloc]initWithResponse:response responseObject:responseObject error:error];
        strongSelf.responseCompletion ? strongSelf.responseCompletion(result) : nil;
        [strongSelf removeDelegateForDataTask];
        [strongSelf logResponseInfo:result];
    }];
    [self.task resume];
}

- (void)logRequestInfo{
#ifdef DEBUG
    if (self.enableLog) {
        NSMutableDictionary *requestHeader = [NSMutableDictionary dictionaryWithDictionary:self.requestHeader];
        if (self.session.config.requestHeader && self.session.config.requestHeader.count > 0) {
            [requestHeader addEntriesFromDictionary:self.session.config.requestHeader];
        }
        
        NSLog(@"\n==================发送请求==================\n\
              \n===请求地址:%@\n\
              \n===图片数组:%@\n\
              \n===图片格式:%@\n\
              \n===图片对应服务器上的字段:%@\n\
              \n===请求参数:%@\n\
              \n===请求头:%@\n\
              \n===========================================",
              self.url,
              self.images,
              self.imageType,
              self.name,
              [self disposePublicParameters],
              requestHeader);
    }
#endif
}

- (void)logResponseInfo:(HLEBaseResponse*)response{
#ifdef DEBUG
    if (self.enableLog) {
        NSLog(@"\n==================请求结束==================\n\
              \n===请求地址:%@\n\
              \n===%@\n\
              \n===========================================",
              self.url,
              (response.success ?
               [NSString stringWithFormat:@"===成功请求返回:%@",response.responseObject] :
               [NSString stringWithFormat:@"===失败请求返回:%@",response.error])
              );
    }
#endif
}
@end
